package com.yololabelmaker;

import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.yololabelmaker.view.DatasetBrowserPanel;

public class CImgOpener {
    private JFileChooser fileChooser;
    private JTextField urlTextField;
    
    public CImgOpener() {
        fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        
        // 设置文件过滤器，只显示支持的图片格式
        fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter(
                "图片文件 (JPG, PNG, GIF)", "jpg", "jpeg", "png", "gif"));
    }
    
    // 打开图片
    public void openImage(CImgArea imgArea) {
        int returnVal = fileChooser.showOpenDialog(imgArea);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                BufferedImage image = ImageIO.read(file);
                if (image != null) {
                    imgArea.setImage(image, file.getAbsolutePath());
                } else {
                    JOptionPane.showMessageDialog(imgArea, "无法打开选定的文件，请确保它是有效的图片文件。");
                }
            } catch (IOException e) {
                JOptionPane.showMessageDialog(imgArea, "打开图片时发生错误: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            // 用户取消选择，尝试打开网络图片
            openNetworkImage(imgArea);
        }
    }
    
    // 打开网络图片
    private void openNetworkImage(CImgArea imgArea) {
        urlTextField = new JTextField(30);
        JPanel panel = new JPanel();
        panel.add(new JLabel("输入图片URL: "));
        panel.add(urlTextField);
        
        int result = JOptionPane.showConfirmDialog(imgArea, panel, "打开网络图片", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String urlString = urlTextField.getText().trim();
            if (!urlString.isEmpty()) {
                try {
                    URL url = new URL(urlString);
                    BufferedImage image = ImageIO.read(url);
                    if (image != null) {
                        // 对于网络图片，我们需要创建一个临时文件路径作为标识
                        String tempPath = "network_image_" + System.currentTimeMillis() + "." + getFileExtensionFromUrl(urlString);
                        imgArea.setImage(image, tempPath);
                    } else {
                        JOptionPane.showMessageDialog(imgArea, "无法从URL加载图片，请检查URL是否正确。");
                    }
                } catch (MalformedURLException e) {
                    JOptionPane.showMessageDialog(imgArea, "无效的URL格式: " + e.getMessage());
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(imgArea, "加载网络图片时发生错误: " + e.getMessage());
                }
            }
        }
    }
    
    // 从URL获取文件扩展名
    private String getFileExtensionFromUrl(String urlString) {
        String extension = "jpg";
        int lastDotIndex = urlString.lastIndexOf('.');
        if (lastDotIndex > 0) {
            String potentialExtension = urlString.substring(lastDotIndex + 1).toLowerCase();
            // 检查是否是有效的图片扩展名
            if (potentialExtension.matches("^(jpg|jpeg|png|gif)$")) {
                extension = potentialExtension;
            }
        }
        return extension;
    }
    
    // 打开数据集目录
    public void openDatasetDirectory(CImgArea imgArea) {
        // 设置文件选择器为目录选择模式
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        
        int returnVal = fileChooser.showOpenDialog(imgArea);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File directory = fileChooser.getSelectedFile();
            
            // 检查目录是否符合YOLO数据集要求
            if (checkDirYoloCompatibility(directory)) {
                // 调用GUI显示数据集的行为
                callBehavior_GUIShowDataset(imgArea, directory);
            } else {
                JOptionPane.showMessageDialog(imgArea, "选定的目录不符合YOLO数据集结构要求。\n请确保目录包含images和labels文件夹。");
            }
        }
        
        // 恢复文件选择器为文件和目录选择模式
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    }
    
    // 检查目录是否符合YOLO数据集兼容性
    public boolean checkDirYoloCompatibility(File directory) {
        // 标准的YOLO数据集通常包含images和labels文件夹
        File imagesDir = new File(directory, "images");
        File labelsDir = new File(directory, "labels");
        
        return directory.exists() && directory.isDirectory() && 
               (imagesDir.exists() && imagesDir.isDirectory() || 
                labelsDir.exists() && labelsDir.isDirectory());
    }
    
    // 调用行为：GUI显示数据集
    private void callBehavior_GUIShowDataset(CImgArea imgArea, File datasetDir) {
        // 创建数据集浏览器对话框
        JDialog datasetDialog = new JDialog((JFrame) SwingUtilities.getWindowAncestor(imgArea), "数据集浏览");
        datasetDialog.setSize(1000, 700);
        datasetDialog.setLocationRelativeTo(imgArea);
        datasetDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        
        // 创建DatasetBrowserPanel并添加到对话框
        DatasetBrowserPanel browserPanel = new DatasetBrowserPanel(imgArea, datasetDir);
        datasetDialog.setContentPane(browserPanel);
        
        datasetDialog.setVisible(true);
    }
    
    // 创建预览图标（用于其他地方的图片预览）
    private ImageIcon createPreviewIcon(BufferedImage image, int maxWidth, int maxHeight) {
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 计算缩放比例
        double scale = Math.min((double) maxWidth / width, (double) maxHeight / height);
        int newWidth = (int) (width * scale);
        int newHeight = (int) (height * scale);
        
        // 创建缩略图
        Image scaledImage = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
        return new ImageIcon(scaledImage);
    }
}